import ctypes
from PIL import ImageTk,Image
import main
# 加载 DLL 文件
libzkfp = ctypes.WinDLL('libzkfp.dll')

# 定义函数参数类型
libzkfp.ZKFPM_Init.argtypes = []
libzkfp.ZKFPM_Init.restype = ctypes.c_int

libzkfp.ZKFPM_Terminate.argtypes = []
libzkfp.ZKFPM_Terminate.restype = ctypes.c_int

libzkfp.ZKFPM_GetDeviceCount.argtypes = []
libzkfp.ZKFPM_GetDeviceCount.restype = ctypes.c_int

libzkfp.ZKFPM_OpenDevice.argtypes = [ctypes.c_int]
libzkfp.ZKFPM_OpenDevice.restype = ctypes.c_void_p

libzkfp.ZKFPM_CloseDevice.argtypes = [ctypes.c_void_p]
libzkfp.ZKFPM_CloseDevice.restype = ctypes.c_int

libzkfp.ZKFPM_AcquireFingerprintImage.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ubyte), ctypes.c_uint]
libzkfp.ZKFPM_AcquireFingerprintImage.restype = ctypes.c_int

device_handle = 0

# 设置图片
def setImage():
    new_image = Image.open("zwy/3-1.jpg")
    new_image = new_image.resize((200, 200), Image.ANTIALIAS)
    new_photo = ImageTk.PhotoImage(new_image)
    main.app.label.config(image=new_photo)
    # 保存对新图片的引用，避免被垃圾回收机制销毁
    main.app.label.image = new_photo


# 初始化库
result = libzkfp.ZKFPM_Init()
if result == 0:
    print("初始化库成功！")
else:
    print(f"初始化库失败，错误代码：{result}")

# 获取设备数
device_count = libzkfp.ZKFPM_GetDeviceCount()
print(f"当前接入指纹仪设备数：{device_count}")

# 打开设备
device_handle = libzkfp.ZKFPM_OpenDevice(0)
# if device_handle:
print("打开设备成功！")


def fingerprint():
    # 创建用于存储指纹图像的缓冲区
    buffer_size = 1024 * 1024  # 假设图像缓冲区大小为1MB
    image_buffer = (ctypes.c_ubyte * buffer_size)()

    # 调用获取指纹图像的函数
    while True:
        acquire_result = libzkfp.ZKFPM_AcquireFingerprintImage(device_handle, image_buffer, buffer_size)
        if acquire_result == 0:
            print("获取指纹图像成功！")
            # 在这里你可以对获取到的指纹图像进行处理，比如保存到文件或者显示在界面上
            image = Image.frombytes('L', (280, 355), bytes(image_buffer), 'raw')
            # 保存图像到文件
            image.save('tmp/fingerprint_image.bmp')
            print("指纹图像已保存为 fingerprint_image.bmp")

def closefinger():
    global device_handle  # 声明为全局变量
    # 关闭设备
    close_result = libzkfp.ZKFPM_CloseDevice(device_handle)
    if close_result == 0:
        print("关闭设备成功！")
    else:
        print(f"关闭设备失败，错误代码：{close_result}")

    # 释放库
    terminate_result = libzkfp.ZKFPM_Terminate()
    if terminate_result == 0:
        print("释放库成功！")
    else:
        print(f"释放库失败，错误代码：{terminate_result}")
